﻿
//潜在客源管理js
var PreCustomerManager = {
    tempTargetEstate: null, //临时的选中目标楼盘，点击确定的时候在页面显示
    tempAssignUser: null, //临时的分配人信息,
    tempAssignDept: null//临时的分配部门信息,
};

//目标楼盘自动完成
PreCustomerManager.getEstateUrl = function () {
    var estateSearchValue = $("#txtEstateSearchValue").val();
    return '/Estate/auto-match-eatate-search-value?EstateSearchType=1&EstateSearchValue=' + escape(estateSearchValue);
};

PreCustomerManager.estateAutoComplete = function () {
    //楼盘自动完成及赋值隐藏域
    $("#txtEstateSearchValue").autocomplete(this.getEstateUrl, {
        width: 260,
        max: 1000,
        Default: 1,
        selectFirst: false,
        cacheLength: 0,
        formatItem: function (row) {
            if (row.ItemFullText != null && row.ItemFullText != "") {
                return row.ItemFullText;
            } else {
                return row.ItemText;
            }
        },
        formatResult: function (row) {
            return row.ItemText;
        }
    }).result(function (a, b) {
        PreCustomerManager.tempTargetEstate = b;
    });
};

PreCustomerManager.addTargetEstate = function () {
    $("#addToTargetEstate").click(function () {
        var that = PreCustomerManager.tempTargetEstate;
        if (that == null) {
            $.OKDialogAgency('<div class="tc">请从智能提示中选择目标楼盘！</div>');
            return false;
        }

        //判断选中的目标楼盘最多为5个
        if ($("#spanAddEstates").find("input[name='EstateKeyId']").length > 4) {
            $.OKDialogAgency('<div class="tc">目标楼盘最多为5个！</div>');
            return false;
        }

        //判断楼盘是否重复
        if ($("#spanAddEstates").find("span input[name='EstateKeyId'][value='" + that.ItemValue + "']").length > 0) {
            $.OKDialogAgency('<div class="tc">不能重复添加楼盘！</div>');
            return false;
        }

        var tempStr = '<span name="{0}" class="l">{1}'
            + '<a><input type="hidden" name="EstateKeyId" value="{2}" />'
            + '<input type="hidden" name="EstateName" value="{1}" />'
            + '<i class="fclose">×</i></a>'
            + '</span>';

        PreCustomerManager.tempTargetEstate = null;
        $("#txtEstateSearchValue").val("");
        //拼接显示的目标楼盘
        $("#spanAddEstates").append(tempStr.format(that.ItemText, that.ItemText, that.ItemValue));
    });
}

//员工分配自动完成
PreCustomerManager.getAssignUserUrl = function () {
    var estateSearchValue = $("#txtAssignUser").val();
    return "/property/user-auto-complete-obtain-ajax?name=" + escape(estateSearchValue) + '&ExceptMe=false&hasPublicAccount=false';
};

PreCustomerManager.assignUserAutoComplete = function () {
    //员工分配自动完成及赋值隐藏域
    $("#txtAssignUser").autocomplete(this.getAssignUserUrl, {
        width: 260,
        max: 1000,
        Default: 1,
        selectFirst: false,
        cacheLength: 0,
        formatItem: function (row) {
            if (row.IsPublicAccount) {
                return row.UserName + "<span style='float:right'>" + row.DepartmentName + "</span>";
            } else {
                return row.UserName + "(" + row.EmployeeNo + ")<span style='float:right'>" + row.DepartmentName + "</span>";
            }
        },
        formatResult: function (row) {
            return row.UserName;
        }
    }).result(function (a, b) {
        PreCustomerManager.tempAssignUser = b;
    });
}

PreCustomerManager.addAssignUser = function () {
    $("#addAssignUser").click(function () {
        var that = PreCustomerManager.tempAssignUser;
        if (that == null) {
            $.OKDialogAgency('<div class="tc">请从智能提示中选择分配人！</div>');
            return false;
        }
        //判断分配人是否重复
        if ($("#spanAddContacts").find("span input[name='AssignUserKeyId'][value='" + that.UserKeyId + "']").length > 0) {
            $.OKDialogAgency('<div class="tc">不能重复添加分配人！</div>');
            return;
        }

        var tempStr = '<span name="{0}" class="l">{1}'
            + '<a><input type="hidden" name="AssignUserKeyId" value="{2}" />'
            + '<input type="hidden" name="AssignUserDeptKeyId" value="{3}" />'
            + '<i class="fclose">×</i></a>'
            + '</span>';

        PreCustomerManager.tempAssignUser = null;
        $("#txtAssignUser").val("");
        //拼接显示
        $("#spanAddContacts").append(tempStr.format(that.UserName, that.UserName, that.UserKeyId, that.DepartmentKeyId));
    });
}

//分配部门
PreCustomerManager.getAssignDeptUrl = function () {
    var deptSearchValue = $("#txtAssignDept").val();
    return "/org/auto-match-department?deptName=" + escape(deptSearchValue) + "&v=" + Math.random();
}

PreCustomerManager.addAssignDeptAutoComplete = function (keyid) {
    $("#txtAssignDept").click(function () {
        $.AjaxAgency("/customer/precustomer-Owner", { keyid: keyid }, function (data) {
            if (data.Flag) {
                $("#tt").tree({
                    url: '/Org/find-lowinheritandself-departments?depaertmentKeyId=' + data.DeptKeyId + '',
                    checkbox: false,
                    method: 'get',
                    animate: true,
                    lines: true,
                    state: "closed",
                    onLoadSuccess: function () {
                        $("#tt").tree("collapseAll");
                        $(".easyui-panel").css("width", "320px");
                    }
                });
            }
        })
    })
};

PreCustomerManager.addAssignDept = function () {
    $("#addAssignDept").click(function () {
        //获取选中项
        //var nodes = $('#tt').tree('getChecked');

        var nodes = $('#tt').tree('getSelected');
        if (nodes == null || nodes.length == 0) {
            $.OKDialogAgency('<div class="tc">请在列表树种选择要分配的部门后点击添加！</div>');
            return false;
        }

        //判断楼盘是否重复
        if ($("#spanAddDept").find("span input[name='AssignDepartmentKeyId'][value='" + nodes.id + "']").length > 0) {
            $.OKDialogAgency('<div class="tc">不能重复添加分配部门！</div>');
            return false;
        }

        var tempStr = '<span name="{0}" class="l">{1}'
            + '<a><input type="hidden" name="AssignDepartmentKeyId" value="{2}" />'
            + '<i class="fclose">×</i></a>'
            + '</span>';

        $("#txtAssignDept").val("");
        var spanHtml = "";
        spanHtml = tempStr.format(nodes.text, nodes.text, nodes.id)
        $("#spanAddDept").append(spanHtml);
    });
}

$(function () {
    //点击清洗完成度触发事件
    $("#gdIndexCustomerList .btnRealSurveyDetail[name='washachievedrate']").click(function () {
        var keyid = $(this).attr("keyid");
        var itotalcount = $(this).attr("dcount");
        $.AjaxAgency("/customer/all-precustomerwashed", { keyid: keyid }, function (data) {
            var shtml = "<table id='datatable' class='data-table data-table-wrap data-table-text'><thead class='thead'><tr><th>类型</th><th>数量</th><th>百分比</th></tr></thead><tbody>";
            if (data.flag && data.length) {
                for (var i = 0; i < data.length; i++) {
                    var res = data[i].CustomerResult;
                    var count = data[i].CustomerWashedCount;
                    shtml += "<tr><td>" + res + "</td>";
                    shtml += "<td>" + count + "</td>";
                    if (itotalcount > 0) {
                        shtml += "<td>" + (count / itotalcount * 100).toFixed(2) + "%" + "</td><tr>";
                    }
                    else {
                        shtml += "<td>0%</td></tr>";
                    }
                }

                shtml += "</tbody></table>";
                $.dialog({
                    id: 'smsdiv',
                    width: 300,
                    lock: true,
                    title: "清洗完成度",
                    content: shtml
                });
            } else {
                $.OKDialogAgency('<div class="tc">无分配数据！</div>');
                return;
            }
        })
    });

    //点击查看触发事件
    $("#gdIndexCustomerList .btnRealSurveyDetail[name='washMan']").click(function () {
        var keyid = $(this).attr("keyid");
        var importCount = $(this).parent().prevAll(":eq(0)").text();
        $.AjaxAgency("/customer/all-precustomerassign", { keyid: keyid }, function (data) {
            var shtml = "<table id='datatable' class='data-table data-table-wrap data-table-text'><thead class='thead'><tr><th>分配明细</th><th>已清洗数</th></tr></thead><tbody>";
            if (data.flag && data.length) {
                for (var i = 0; i < data.length; i++) {
                    var res = data[i].Name;
                    var count = data[i].DistributionCount;
                    shtml += "<tr><td>" + res + "</td>";
                    shtml += "<td>" + count + "</td></tr>";
                }

                shtml += "</tbody></table>";
                $.dialog({
                    id: 'smsdiv',
                    width: 300,
                    lock: true,
                    title: "分配员工",
                    content: shtml
                });
            }
            else {
                $.OKDialogAgency('<div class="tc">无分配数据！</div>');
                return false;
            }
        })
    });

    //点击再次分配触发事件
    $("#gdIndexCustomerList .btnRealSurveyDetail[name='distriuteCustomer']").click(function () {
        var keyId = $(this).attr("keyid");
        var importNo = $(this).attr("importno");
        var trustorId = $(this).attr("isTrustor");
        var deptId = $(this).attr("deptkey");
        if (keyId) {
            $.dialog({
                id: 'tempprecusdistribute",',
                init: function () {
                    PreCustomerManager.estateAutoComplete();
                    PreCustomerManager.addTargetEstate();
                    PreCustomerManager.assignUserAutoComplete();
                    PreCustomerManager.addAssignUser();
                    PreCustomerManager.addAssignDeptAutoComplete(keyId);
                    PreCustomerManager.addAssignDept();
                    //x样式的删除
                    $(".fclose").live("click", function () {
                        $(this).parent().parent().remove();
                    });
                    if (trustorId == 1) {
                        $("#IsTrustor").hide();
                        $("#cusIsTrustor").val(true);
                    } else {
                        $("#IsTrustor").show();
                        $("#cusIsTrustor").val(false);
                    }
                },
                title: "再次分配",
                content: $("#layerPreCusAssign").html(),
                ok: function () {
                    
                    if (!$("#spanAddContacts a").length) {
                        if (!$("#spanAddDept a").length) {
                            $.OKDialogAgency('<div class="tc">部门分配与员工分配必填一项！</div>');
                            return false;
                        }
                    }

                    $("#cusKeyId").val(keyId);
                    $("#cusImportNo").val(importNo);
                    var reqData = $("#assginForm").serializeArray();
                    $.AjaxAgency("/customer/assignagain-precustomer", reqData, function (data) {
                        if (data.Flag) {
                            $.dialog({
                                content: '<div class="tc">再次分配成功！</div>',
                                lock: true,
                                ok: function () {
                                    window.location.href = window.location.href;
                                },
                                cancel: false
                            });
                        } else {
                            if (data.ErrorMsg) {
                                $.OKDialogAgency("<div class='tc'>" + data.ErrorMsg + "</div>");
                            }
                            else {
                                $.OKDialogAgency("<div class='tc'>" + data + "</div>");
                            }

                            return false;
                        }
                    });
                },
                cancel: true
            })
        }
    })
});